package com.hck.trigger.http;


import com.hck.domain.consultation.model.entity.ConsultationReplyEntity;
import com.hck.domain.consultation.model.entity.HealthConsultationEntity;
import com.hck.domain.consultation.service.IConsultationService;
import com.hck.types.model.PageRequest;
import com.hck.types.model.PageResponse;
import com.hck.types.model.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/consultation")
@Tag(name = "咨询接口", description = "咨询相关操作")
public class ConsultationController {

    @Resource
    private IConsultationService consultationService;

    // 创建咨询
    @PostMapping("/create")
    @Operation(summary = "用户咨询", description = "用户咨询")
    public Response<Long> createConsultation(@RequestBody HealthConsultationEntity consultation) {
        Long id = consultationService.createConsultation(consultation);
        return Response.<Long>builder()
                .info("创建咨询成功")
                .data(id)
                .code("200")
                .build();
    }

    // 回复咨询
    @PostMapping("/{id}/reply")
    @Operation(summary = "医生回复咨询", description = "医生回复咨询")
    public Response<Void> replyConsultation(@PathVariable Long id, @RequestBody ConsultationReplyEntity reply) {
        consultationService.replyConsultation(id, reply);
        return Response.<Void>builder()
                .info("回复咨询成功")
                .data(null)
                .code("200")
                .build();
    }

    // 查询咨询详情
    @GetMapping("/{id}")
    @Operation(summary = "查询咨询详情", description = "查询咨询详情")
    public Response<HealthConsultationEntity> getConsultationDetail(@PathVariable Long id) {
        return Response.<HealthConsultationEntity>builder()
                .code("200")
                .data(consultationService.getConsultationDetail(id))
                .info("查询成功")
                .build();
    }

    // 查询咨询回复
    @GetMapping("/{id}/replies")
    @Operation(summary = "查询咨询回复", description = "查询咨询回复")
    public Response<List<ConsultationReplyEntity>> getReplies(@PathVariable Long id) {
        return Response.<List<ConsultationReplyEntity>>builder()
                .code("200")
                .data(consultationService.getReplies(id))
                .info("查询成功")
                .build();
    }

    // 查询用户的咨询列表
    @GetMapping("/user/{userId}")
    @Operation(summary = "查询用户的咨询列表", description = "查询用户的咨询列表")
    public Response<List<HealthConsultationEntity>> getUserConsultations(@PathVariable Long userId) {
        return Response.<List<HealthConsultationEntity>>builder()
                .code("200")
                .data(consultationService.getUserConsultations(userId))
                .info("查询成功")
                .build();
    }

    // 分页查询用户的咨询列表
    @GetMapping("/user/{userId}/page")
    @Operation(summary = "分页查询用户的咨询列表", description = "分页查询用户的咨询列表")
    public Response<PageResponse<HealthConsultationEntity>> getUserConsultationsPage(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "6") Integer pageSize) {
        
        PageRequest pageRequest = PageRequest.builder()
                .pageNum(pageNum)
                .pageSize(pageSize)
                .build();
        
        return Response.<PageResponse<HealthConsultationEntity>>builder()
                .code("200")
                .data(consultationService.getUserConsultationsPage(userId, pageRequest))
                .info("查询成功")
                .build();
    }

    // 查询医生的咨询列表
    @GetMapping("/doctor/{doctorId}")
    @Operation(summary = "查询医生的咨询列表", description = "查询医生的咨询列表")
    public Response<List<HealthConsultationEntity>> getDoctorConsultations(@PathVariable Long doctorId) {
        return Response.<List<HealthConsultationEntity>>builder()
                .code("200")
                .data(consultationService.getDoctorConsultations(doctorId))
                .info("查询成功")
                .build();
    }
    
    // 分页查询医生的咨询列表
    @GetMapping("/doctor/{doctorId}/page")
    @Operation(summary = "分页查询医生的咨询列表", description = "分页查询医生的咨询列表")
    public Response<PageResponse<HealthConsultationEntity>> getDoctorConsultationsPage(
            @PathVariable Long doctorId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "6") Integer pageSize) {
        
        PageRequest pageRequest = PageRequest.builder()
                .pageNum(pageNum)
                .pageSize(pageSize)
                .build();
        
        return Response.<PageResponse<HealthConsultationEntity>>builder()
                .code("200")
                .data(consultationService.getDoctorConsultationsPage(doctorId, pageRequest))
                .info("查询成功")
                .build();
    }

    @PostMapping("/{id}/close")
    @Operation(summary = "结束咨询会话", description = "将会话状态设为closed")
    public Response<Void> closeConsultation(@PathVariable Long id) {
        consultationService.closeConsultation(id);
        return Response.<Void>builder()
                .info("会话已结束")
                .data(null)
                .code("200")
                .build();
    }

    @PostMapping("/ai-chat")
    @Operation(summary = "AI健康咨询对话", description = "AI健康咨询对话")
    public Response<String> aiChat(@RequestBody Map<String, String> body) {
        String userMessage = body.get("message");
        if (userMessage == null || userMessage.trim().isEmpty()) {
            return Response.<String>builder().code("400").data("").info("用户问题不能为空").build();
        }
        String apiKey = "sk-18b86ab965404c8fb203f9546c6d40fd";
        String apiUrl = "https://api.deepseek.com/v1/chat/completions";

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        // 构造messages参数，必须为List<Map<String, String>>
        java.util.List<java.util.Map<String, String>> messages = new java.util.ArrayList<>();
        java.util.Map<String, String> systemMsg = new java.util.HashMap<>();
        systemMsg.put("role", "system");
        systemMsg.put("content", "You are a helpful assistant.");
        messages.add(systemMsg);
        java.util.Map<String, String> userMsg = new java.util.HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", userMessage);
        messages.add(userMsg);

        java.util.Map<String, Object> requestBody = new java.util.HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2048);
        requestBody.put("stream", false);

        HttpEntity<java.util.Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
        try {
            ResponseEntity<java.util.Map> response = restTemplate.postForEntity(apiUrl, entity, java.util.Map.class);
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Object choicesObj = response.getBody().get("choices");
                if (choicesObj instanceof java.util.List && !((java.util.List<?>) choicesObj).isEmpty()) {
                    java.util.Map<?, ?> choice = (java.util.Map<?, ?>) ((java.util.List<?>) choicesObj).get(0);
                    java.util.Map<?, ?> message = (java.util.Map<?, ?>) choice.get("message");
                    String aiReply = message != null ? (String) message.get("content") : "AI无回复";
                    return Response.<String>builder().code("200").data(aiReply).info("AI回复成功").build();
                }
            }
            return Response.<String>builder().code("500").data("").info("AI回复失败").build();
        } catch (Exception e) {
            return Response.<String>builder().code("500").data("").info("AI服务异常: " + e.getMessage()).build();
        }
    }
}